package com.landeb.shop.huo.act;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.ActControler;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.VersionManager;
import com.landeb.shop.huo.bean.BeanVersion;
import com.landeb.shop.huo.httpRequest.VersionRequest;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class VersionActivity extends BaseActivity {
    private TextView mTvVersion;
    private Button mBtnCheckVersion;
    private OkHttpClient mClient;
    private String mUrl;
    private Retrofit mRetrofit;
    private VersionRequest mRequest;
    private String downloadUrl = "";

    public static void toAct(Context context) {
        context.startActivity(new Intent(context, VersionActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_version);


        mClient = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(mClient)
                .build();
        mRequest = mRetrofit.create(VersionRequest.class);

        mBtnCheckVersion = (Button) findViewById(R.id.act_version_btn_checkVersion);
        mTvVersion = (TextView) findViewById(R.id.act_version_tv_getVersionName);

        mTvVersion.setText("当前版本：" + VersionManager.getVersionName(VersionActivity.this));

        mBtnCheckVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017/8/24 升级方法
                checkUpdate();
            }
        });
    }


    private void checkUpdate() {



        final ProgressDialog progressDialog = new ProgressDialog(VersionActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在更新，请稍后");
        progressDialog.show();

            mRequest.getVersion("0")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanVersion>() {
                        @Override
                        public void onCompleted() {
                            Log.e("getVersion", "onCompleted: ");
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("getVersion", "onError: " + e.toString());
                            progressDialog.dismiss();

                        }

                        @Override
                        public void onNext(BeanVersion beanVersion) {
                            if (beanVersion.getStatus() == 1) {

                                final String newVer = beanVersion.getData().getV();
                                String title = beanVersion.getData().getTitle();
                                String msg = beanVersion.getData().getUpdate();
                                final String forceTitle = beanVersion.getData().getForce_title();
                                final String forceMsg = beanVersion.getData().getForce_content();
                                final String forceFlag = beanVersion.getData().getForce();
                                downloadUrl = beanVersion.getData().getDownload();


                                AlertDialog.Builder builder = new AlertDialog.Builder(VersionActivity.this);

                                if (forceFlag.equals("1")) {

                                    builder.setTitle(title)
                                            .setMessage(msg)
                                            .setCancelable(false)
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    // TODO: 2016/11/28 强制升级
                                                    forceUpdate();

                                                }
                                            }).show();
                                } else {

                                    builder.setTitle("检测到新版本")
                                            .setMessage(msg)
                                            .setCancelable(false)
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    // TODO: 2016/11/28 普通升级
                                                    forceUpdate();
                                                }
                                            })
                                            .setNegativeButton("取消", null)
                                            .show();

                                }


                            }
                        }
                    });


    }

    public void forceUpdate() {
//      UpdateService.Builder builder=UpdateService.Builder.create(downloadUrl).build(this);

        final String path = getExternalFilesDir(null) + File.separator + System.currentTimeMillis() + ".apk";

        final ProgressDialog progressDialog = new ProgressDialog(VersionActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在更新，请稍后");
        progressDialog.show();

        FileDownloader.getImpl().create(downloadUrl)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                        double pro = (double) soFarBytes / totalBytes * 100;
                        int progress = (int) Math.ceil(pro);
                        progressDialog.setProgress(progress);

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        progressDialog.dismiss();

                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
                        startActivity(intent);

                        ActControler.removeAllAct();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        progressDialog.dismiss();
                        Toast.makeText(VersionActivity.this, "网络异常，请稍后重试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                }).start();


    }

}
